import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
// 云端服务类
class CloudService {
    private List<EdgeDevice> edgeDevices;
    private ScheduledExecutorService scheduler;
    private DefaultListModel<String> logModel;

    public CloudService(DefaultListModel<String> logModel) {
        this.edgeDevices = new ArrayList<>();
        this.scheduler = Executors.newScheduledThreadPool(1);
        this.logModel = logModel;
    }

    public void registerDevice(EdgeDevice device) {
        edgeDevices.add(device);
        log("注册设备: " + device.getDeviceId() + " - " + device.getLocation() +
                (device.isUsingFixedTiming() ? " (固定时长)" : " (云端优化)"));
    }

    //延时30秒后，以30秒为周期，对注册的云端优化设备进行当前信号灯的时长更新
    public void startOptimization() {
        scheduler.scheduleAtFixedRate(() -> {
            log("开始全局优化...");

            // 收集需要优化的设备数据
            Map<EdgeDevice, Map<Integer, Integer>> optimizationData = new HashMap<>();
            for (EdgeDevice device : edgeDevices) {
                if (!device.isUsingFixedTiming()) {
                    optimizationData.put(device, device.getSignalTiming());
                }
            }

            // 执行全局优化
            Map<EdgeDevice, Map<Integer, Integer>> optimizedTimings = optimizeGlobally(optimizationData);

            // 应用优化结果
//            optimizedTimings.forEach(EdgeDevice::updateFromCloud);

        }, 30, 30, TimeUnit.SECONDS);
    }
    // CloudService.java
    private Map<EdgeDevice, Map<Integer, Integer>> optimizeGlobally(
            Map<EdgeDevice, Map<Integer, Integer>> currentTimings) {

        Map<EdgeDevice, Map<Integer, Integer>> optimized = new HashMap<>();

        // 模拟全局优化算法（实际项目替换为真实算法）
        currentTimings.forEach((device, timing) -> {
            Map<Integer, Integer> newTiming = new HashMap<>();
            Random rand = new Random();

            // 根据设备类型采用不同优化策略
            if (device.isSchoolZone()) {
                // 学校区域优化策略（更保守）
                newTiming.put(1, Math.min(45, Math.max(15, timing.get(1) + rand.nextInt(7) - 3)));
                newTiming.put(2, Math.min(45, Math.max(15, timing.get(2) + rand.nextInt(7) - 3)));
            } else {
                // 市中心优化策略（更灵活）
                newTiming.put(1, Math.min(60, Math.max(10, timing.get(1) + rand.nextInt(11) - 5)));
                newTiming.put(2, Math.min(60, Math.max(10, timing.get(2) + rand.nextInt(11) - 5)));
            }

            optimized.put(device, newTiming);

            log("优化结果: " + device.getDeviceId() +
                    " 车道1:" + newTiming.get(1) + "秒, 车道2:" + newTiming.get(2) + "秒");
        });

        return optimized;
    }

    private void log(String message) {
        SwingUtilities.invokeLater(() -> {
            logModel.addElement(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")) +
                    " - [云端] " + message);
        });
    }

    public List<EdgeDevice> getDevices() { return edgeDevices; }
}